package com.yifi.common.plugins;

import com.jfinal.plugin.IPlugin;
import com.jfinal.plugin.activerecord.IDataSourceProvider;
import io.gitee.yaoshanli.engine.FlowEngine;
import io.gitee.yaoshanli.engine.db.JwDbHelper;
import io.gitee.yaoshanli.engine.service.impl.FlowEngineImpl;

import javax.sql.DataSource;
import java.util.Properties;

public class JwFlowPlugin implements IPlugin {

    private static boolean isStarted = false;
    private static DataSource dataSource;
    private static Properties properties;
    private static IDataSourceProvider dataSourceProvider;
    private static FlowEngine engine;

    public JwFlowPlugin(DataSource dataSource) {
        this.dataSource=dataSource;
    }
    public JwFlowPlugin(IDataSourceProvider dataSourceProvider) {
        this.dataSourceProvider=dataSourceProvider;
    }

    @Override
    public boolean start() {
        if (isStarted)
            return true;

        if(dataSourceProvider!=null)
        {
            dataSource = dataSourceProvider.getDataSource();
        }
        if(dataSource==null)
        {
            throw new RuntimeException("JwFlowPlugin start error: JwFlowPlugin need DataSource");
        }
        JwDbHelper.initialize(dataSource);
        engine=new FlowEngineImpl();
        isStarted = true;
        return true;
    }

    @Override
    public boolean stop() {
        JwDbHelper.close();
        isStarted = false;
        return true;
    }

    public static FlowEngine getEngine() {
        return engine;
    }
}
